package udpchatdemo02;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 实现相互发送接收消息
 *      通过多线程，
 *      发送端两个线程：
 *          一个发送端线程，用来发送消息
 *          一个接收端线程，用来接收消息
 *
 * 发送端类
 */
public class TalkSend implements Runnable{
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true){
            // 准备打包发送的数据，监听控制台输入
            reader = new BufferedReader(new InputStreamReader(System.in));

            String s = null;
            try {
                s = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] data = s.getBytes();
            DatagramPacket packet = new DatagramPacket(data, 0, data.length, new InetSocketAddress(toIP, toPort));

            // 发送消息包裹
            try {
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (s.equals("bye")){
                break;
            }
        }
        // 关闭 socket
        socket.close();
    }
}
